<?php
namespace app\helpers;

/**
 * 乱七八糟的函数
 */
class Extra {
    /**
     * 创建UUID
     *
     * @access public
     * @param  string $namespace
     * @return void
     */
    public static function create_uuid($namespace = '') {
        $uid  = uniqid("", true);
        $data = $namespace;
        $data .= $_SERVER['REQUEST_TIME'];
        $data .= $_SERVER['HTTP_USER_AGENT'];
        $data .= $_SERVER['SERVER_ADDR'];
        $data .= $_SERVER['SERVER_PORT'];
        $data .= $_SERVER['REMOTE_ADDR'];
        $data .= $_SERVER['REMOTE_PORT'];
        $hash = strtoupper(hash('ripemd128', $uid . md5($data)));
        return substr($hash, 0, 32);
    }

    public static function getTimeNum($timezoneStr = '') {
        $dateTime = new \DateTime();
        $dateTime->setTimeZone(new \DateTimeZone($timezoneStr));
        switch ($dateTime->format('T')) {
        case 'EST': // Eastern Standard Time 东部标准时间，UTC-0500
            return 1;
            break;
        case 'PST': // Pacific Standard Time 太平洋标准时间，UTC-0800
            return 2;
            break;
        case 'UTC': // Universal Time Coordinated 通用协调时间
            return 3;
            break;
        case 'GMT': // Greenwich Mean Time 格林尼治平均时 UTC=GMT
            return 3;
            break;
        case 'HKT': // 香港时间
            return 4;
            break;
        case 'EDT': // Eastern Daylight Time 东部夏令时(或）东部日光时间，UTC-0400
            return 5;
            break;
        case 'IST':
            return 6;
            break;
        case 'PDT':
            return 7;
            break;
        case 'CST':
            return 8;
            break;

        default:
            return 0;
            break;
        }
    }

    public static function getTimezone($num, $return_all = false) {
        $area_array = [
            1 => 'EST',
            2 => 'PST',
            3 => 'GMT',
            4 => 'HKT',
            5 => 'EDT',
            6 => 'IST',
            7 => 'PDT',
            8 => 'CST',
        ];
        if ($return_all === true) {
            return $area_array;
        }
        $num = trim($num);
        if (!in_array($num, array_keys($area_array))) {
            return '';
        }

        return $area_array[$num];
    }

    /**
     * 创建临时文件
     *
     * @access public
     * @param  void   $name
     * @param  void   $content
     * @return void
     */
    public static function temporaryFile($name, $content) {
        $file = sys_get_temp_dir() .
        DIRECTORY_SEPARATOR .
        ltrim($name, DIRECTORY_SEPARATOR);

        file_put_contents($file, $content);

        register_shutdown_function(function () use ($file) {
            unlink($file);
        });

        return $file;
    }
}
